<template>
    <el-dialog :title="title" width="max-content" :visible.sync="show" center :before-close="cancel">
        <div v-if="list.length">
            <el-table :data="list" maxHeight="500">
                <el-table-column label="变体" align="center" width="200px" prop="sku">

                </el-table-column>
                <el-table-column label="库存" align="center" width="200px">
                    <template slot-scope="scope">
                        <el-input @input="handleStockChange(scope.row)" v-model="scope.row.stock"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="stock-wrapper" v-else>
            <div class="label">
                库存
            </div>
            <el-input @input="handleStockChange()" v-model="myStock"></el-input>
        </div>
        <div slot="footer">
            <el-button @click="confirm" type="primary">
                确定
            </el-button>
            <el-button @click="cancel">
                取消
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
export default {
    props: {
        list: {
            type: Array,
            default: () => []
        },
        stock: {
            type: [Number, String]
        },
        show: {
            type: Boolean,
        },
        title: {
            type: String,
            value: "修改库存"
        },
    },
    model: {
        event: 'showChange',
        prop: 'show',
    },
    watch: {
        stock(val) {
            this.myStock = val
        }
    },
    data() {
        return {
            myStock: ""
        }
    },
    methods: {
        handleStockChange(row) {
            if (row) {
                row.stock = row.stock.replace(/[^0-9]|^0/g, "")
            } else {
                this.myStock = this.myStock.replace(/[^0-9]|^0/g, "")
            }
        },
        confirm() {
            const { list, myStock } = this
            if (list.length && list.some(item => !item.stock) || !list.length && !myStock) {
                this.$message.error("请补充完整库存")
                return
            }
            const params = {
                list,
                stock: myStock
            }
            this.$emit('modifyStock', params)
        },
        cancel() {
            this.$emit("showChange", false)
        }
    },



}
</script>

<style lang="scss" scoped>
.stock-wrapper {
    display: flex;
    align-items: center;

    .label {
        width: 50px;
    }
}
</style>